package com.example.knowledge.component.webview;

import static android.view.View.GONE;

import android.graphics.Bitmap;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.example.knowledge.R;
import com.example.knowledge.activity.BaseActivity;
import com.example.knowledge.android.LBS.LocationUtil;
import com.example.knowledge.bean.HybridEntity;
import com.example.knowledge.bean.TopBarData;
import com.example.knowledge.image.glide.GlideSvgUtil;
import com.fifedu.lib_common_utils.log.LogUtils;
import com.google.gson.Gson;


public class WebViewActivity extends BaseActivity {
    private final String TAG = "WebViewActivity";
    WebView mWebview;
    ImageView mSvgIV;
    String localURL = "file:///android_asset/index.html";
    String webURL = "http://www.baidu.com/";
    String svgUrl = "https://test.fifedu.com/static/fiftest//upload/image/20220426/86fde1bb67924d339c2de7d17b55e7b5.svg";

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {
        mWebview = findViewById(R.id.webview);
        mSvgIV = findViewById(R.id.iv_svg);
        mWebview.addJavascriptInterface(new CommonJSInterface(), "androidInjected");
    }

    public void onResume() {
        super.onResume();
        initSetting(mWebview);
//        initWebViewClient();
        initChromeClient();
        mWebview.loadUrl(webURL);
    }

    @Override
    public void initData() {
//        GlideSvgUtil.showSvgUrl(mSvgIV, svgUrl);
//        GlideSvgUtil.showSvgRes(mSvgIV,R.raw.svg_symbol);
    }



    public static void initSetting(WebView webView) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        WebView.setWebContentsDebuggingEnabled(false);
        //允许缓存，加快页面加载速度
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setSavePassword(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(true);
        //设置页面自适应
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        //userAgent必须这样写，不这样不能成功加载网页url
        String userAgent = webSettings.getUserAgentString();
        webSettings.setUserAgentString(userAgent + " kyxl");
        WebView.setWebContentsDebuggingEnabled(false);
    }

    private void initWebViewClient() {
        //设置WebViewClient类
        mWebview.setWebViewClient(new WebViewClient() {
            //设置加载前的函数
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

            }

            //设置结束加载函数
            @Override
            public void onPageFinished(WebView view, String url) {

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //设置不用系统浏览器打开,直接显示在当前Webview
//                view.loadUrl(url);
                return true;
            }
        });
    }

    private void initChromeClient() {
        //设置WebChromeClient类
        mWebview.setWebChromeClient(new WebChromeClient() {
            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                mTitleTv.setText(title);
            }

            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
            mWebview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public class CommonJSInterface {
        @JavascriptInterface
        public void webCallNative(final String json) {
            LogUtils.d(TAG, "webCallNative: " + json);
            final Gson gson = new Gson();
            final HybridEntity hybridEntity = gson.fromJson(json, HybridEntity.class);
            final String callNativeAction = hybridEntity.getAppAction();
            final String callWebAction = hybridEntity.getWebAction();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (JSUtil.getUserCurrentLocation.equals(callNativeAction)) {
                        final LocationUtil locationUtil = new LocationUtil(WebViewActivity.this);
                        locationUtil.handleLocation(mWebview, callNativeAction, callWebAction);
                    } else if (JSUtil.modifyNavigationBarStyle.equals(callNativeAction)) {
                        TopBarData data = hybridEntity.getTopBarData();
                        if (Integer.parseInt(data.navigationBarType) == 2) {
                            rl_title.setVisibility(GONE);
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyWebView();
    }

    private void destroyWebView() {
        if (mWebview != null) {
            mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebview.clearHistory();
            ((ViewGroup) mWebview.getParent()).removeView(mWebview);
            mWebview.destroy();
            mWebview = null;
        }
    }

}
